<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>科研-产线协同甘特图</title>
    
    <!-- Bootstrap CSS -->
    <link href="https://cdn.bootcdn.net/ajax/libs/bootstrap/5.3.2/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link href="https://cdn.bootcdn.net/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Microsoft YaHei', sans-serif;
            background-color: #f8f9fa;
        }
        
        .gantt-container {
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            margin: 20px;
            padding: 20px;
        }
        
        #ganttChart {
            position: relative;
            overflow-x: auto;
            min-height: 400px;
        }
        
        .task-bar {
            position: absolute;
            height: 30px;
            border-radius: 15px;
            cursor: move;
            display: flex;
            align-items: center;
            padding: 0 10px;
            font-size: 12px;
            color: white;
            font-weight: 500;
            transition: all 0.3s ease;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .task-bar:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.2);
        }
        
        .task-bar.tech {
            background: linear-gradient(135deg, #3498db, #2980b9);
        }
        
        .task-bar.prod {
            background: linear-gradient(135deg, #e74c3c, #c0392b);
        }
        
        .progress-bar {
            position: absolute;
            top: 0;
            left: 0;
            height: 100%;
            background: rgba(255,255,255,0.3);
            border-radius: 15px;
            transition: width 0.3s ease;
        }
        
        .timeline-header {
            display: flex;
            border-bottom: 1px solid #dee2e6;
            margin-bottom: 10px;
            padding-bottom: 10px;
        }
        
        .timeline-label {
            width: 200px;
            font-weight: 600;
            padding: 10px;
            background: #f8f9fa;
            border-right: 1px solid #dee2e6;
        }
        
        .timeline-dates {
            flex: 1;
            display: flex;
            overflow-x: auto;
        }
        
        .date-cell {
            min-width: 40px;
            text-align: center;
            font-size: 12px;
            padding: 5px;
            border-right: 1px solid #e9ecef;
        }
        
        .task-row {
            display: flex;
            align-items: center;
            margin-bottom: 5px;
            height: 40px;
            border-bottom: 1px solid #f1f3f4;
        }
        
        .task-label {
            width: 200px;
            padding: 10px;
            font-weight: 500;
            border-right: 1px solid #dee2e6;
            background: white;
        }
        
        .task-timeline {
            flex: 1;
            position: relative;
            height: 40px;
            background: repeating-linear-gradient(
                90deg,
                #f8f9fa,
                #f8f9fa 39px,
                #e9ecef 39px,
                #e9ecef 40px
            );
        }
        
        .toolbar {
            background: white;
            padding: 15px;
            margin: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .zoom-controls {
            display: inline-flex;
            gap: 10px;
            align-items: center;
        }
        
        .legend {
            display: flex;
            gap: 20px;
            align-items: center;
            margin-left: auto;
        }
        
        .legend-item {
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 14px;
        }
        
        .legend-color {
            width: 20px;
            height: 20px;
            border-radius: 3px;
        }
        
        .modal-body .form-group {
            margin-bottom: 15px;
        }
        
        .group-header {
            background: #f8f9fa;
            font-weight: 600;
            padding: 10px;
            margin: 10px 0;
            border-radius: 4px;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <h1 class="text-center mt-4 mb-4">
            <i class="fas fa-chart-gantt"></i> 科研-产线协同甘特图
        </h1>
        
        <div class="toolbar">
            <div class="d-flex justify-content-between align-items-center">
                <div class="zoom-controls">
                    <button class="btn btn-outline-primary" onclick="zoomIn()">
                        <i class="fas fa-search-plus"></i> 放大
                    </button>
                    <button class="btn btn-outline-primary" onclick="zoomOut()">
                        <i class="fas fa-search-minus"></i> 缩小
                    </button>
                    <button class="btn btn-outline-secondary" onclick="resetZoom()">
                        <i class="fas fa-expand-arrows-alt"></i> 重置
                    </button>
                </div>
                
                <div class="legend">
                    <div class="legend-item">
                        <div class="legend-color" style="background: linear-gradient(135deg, #3498db, #2980b9);"></div>
                        <span>技术研发组</span>
                    </div>
                    <div class="legend-item">
                        <div class="legend-color" style="background: linear-gradient(135deg, #e74c3c, #c0392b);"></div>
                        <span>产线建设组</span>
                    </div>
                </div>
                
                <div>
                    <button class="btn btn-success" onclick="exportExcel()">
                        <i class="fas fa-file-excel"></i> 导出Excel
                    </button>
                    <button class="btn btn-info" onclick="exportImage()">
                        <i class="fas fa-image"></i> 导出图片
                    </button>
                </div>
            </div>
        </div>
        
        <div class="gantt-container">
            <div id="ganttChart">
                <div class="timeline-header">
                    <div class="timeline-label">任务名称</div>
                    <div class="timeline-dates" id="timelineDates"></div>
                </div>
                <div id="ganttContent"></div>
            </div>
        </div>
    </div>
    
    <!-- 任务编辑模态框 -->
    <div class="modal fade" id="taskModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">编辑任务</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="taskForm">
                        <div class="form-group">
                            <label>任务名称</label>
                            <input type="text" class="form-control" id="taskName" readonly>
                        </div>
                        <div class="form-group">
                            <label>开始日期</label>
                            <input type="date" class="form-control" id="taskStart">
                        </div>
                        <div class="form-group">
                            <label>结束日期</label>
                            <input type="date" class="form-control" id="taskEnd">
                        </div>
                        <div class="form-group">
                            <label>进度 (%)</label>
                            <input type="range" class="form-range" id="taskProgress" min="0" max="100" value="0">
                            <span id="progressValue">0%</span>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="saveTask()">保存</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Bootstrap JS -->
    <script src="https://cdn.bootcdn.net/ajax/libs/bootstrap/5.3.2/js/bootstrap.bundle.min.js"></script>
    
    <script>
        let tasksData = null;
        let zoomLevel = 1;
        let currentTask = null;
        
        // 初始化
        document.addEventListener('DOMContentLoaded', function() {
            loadTasks();
            
            // 进度条实时更新
            document.getElementById('taskProgress').addEventListener('input', function(e) {
                document.getElementById('progressValue').textContent = e.target.value + '%';
            });
        });
        
        // 加载任务数据
        async function loadTasks() {
            try {
                const response = await fetch('/api/tasks');
                tasksData = await response.json();
                renderGantt();
            } catch (error) {
                console.error('加载任务失败:', error);
            }
        }
        
        // 渲染甘特图
        function renderGantt() {
            const timelineDates = document.getElementById('timelineDates');
            const ganttContent = document.getElementById('ganttContent');
            
            // 清空现有内容
            timelineDates.innerHTML = '';
            ganttContent.innerHTML = '';
            
            // 计算日期范围
            const allDates = [];
            tasksData.tasks.forEach(task => {
                allDates.push(new Date(task.start));
                allDates.push(new Date(task.end));
            });
            
            const minDate = new Date(Math.min(...allDates));
            const maxDate = new Date(Math.max(...allDates));
            
            // 添加月份
            const months = [];
            let current = new Date(minDate);
            current.setDate(1);
            
            while (current <= maxDate) {
                months.push(new Date(current));
                current.setMonth(current.getMonth() + 1);
            }
            
            // 渲染时间轴
            months.forEach(date => {
                const cell = document.createElement('div');
                cell.className = 'date-cell';
                cell.textContent = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`;
                cell.style.width = `${100 * zoomLevel}px`;
                timelineDates.appendChild(cell);
            });
            
            // 按组分组任务
            const groupedTasks = {};
            tasksData.groups.forEach(group => {
                groupedTasks[group.id] = {
                    name: group.name,
                    color: group.color,
                    tasks: tasksData.tasks.filter(task => task.group === group.id)
                };
            });
            
            // 渲染任务
            Object.entries(groupedTasks).forEach(([groupId, group]) => {
                // 组标题
                const groupHeader = document.createElement('div');
                groupHeader.className = 'group-header';
                groupHeader.textContent = group.name;
                ganttContent.appendChild(groupHeader);
                
                // 组内任务
                group.tasks.forEach(task => {
                    const taskRow = document.createElement('div');
                    taskRow.className = 'task-row';
                    
                    const taskLabel = document.createElement('div');
                    taskLabel.className = 'task-label';
                    taskLabel.textContent = task.name;
                    
                    const taskTimeline = document.createElement('div');
                    taskTimeline.className = 'task-timeline';
                    
                    // 计算任务条位置和宽度
                    const taskStart = new Date(task.start);
                    const taskEnd = new Date(task.end);
                    const totalDays = (maxDate - minDate) / (1000 * 60 * 60 * 24);
                    const daysFromStart = (taskStart - minDate) / (1000 * 60 * 60 * 24);
                    const taskDuration = (taskEnd - taskStart) / (1000 * 60 * 60 * 24);
                    
                    const pixelsPerDay = (months.length * 100 * zoomLevel) / totalDays;
                    const left = daysFromStart * pixelsPerDay;
                    const width = taskDuration * pixelsPerDay;
                    
                    const taskBar = document.createElement('div');
                    taskBar.className = `task-bar ${groupId == 0 ? 'tech' : 'prod'}`;
                    taskBar.style.left = `${left + 200}px`;
                    taskBar.style.width = `${width}px`;
                    taskBar.style.top = '5px';
                    taskBar.textContent = task.name;
                    taskBar.dataset.taskId = task.id;
                    
                    const progressBar = document.createElement('div');
                    progressBar.className = 'progress-bar';
                    progressBar.style.width = `${task.progress}%`;
                    taskBar.appendChild(progressBar);
                    
                    taskBar.addEventListener('click', () => openTaskModal(task));
                    
                    taskTimeline.appendChild(taskBar);
                    taskRow.appendChild(taskLabel);
                    taskRow.appendChild(taskTimeline);
                    ganttContent.appendChild(taskRow);
                });
            });
        }
        
        // 打开任务编辑模态框
        function openTaskModal(task) {
            currentTask = task;
            document.getElementById('taskName').value = task.name;
            document.getElementById('taskStart').value = task.start;
            document.getElementById('taskEnd').value = task.end;
            document.getElementById('taskProgress').value = task.progress;
            document.getElementById('progressValue').textContent = task.progress + '%';
            
            const modal = new bootstrap.Modal(document.getElementById('taskModal'));
            modal.show();
        }
        
        // 保存任务
        async function saveTask() {
            if (!currentTask) return;
            
            const updatedTask = {
                start: document.getElementById('taskStart').value,
                end: document.getElementById('taskEnd').value,
                progress: parseInt(document.getElementById('taskProgress').value)
            };
            
            try {
                const response = await fetch(`/api/tasks/${currentTask.id}`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(updatedTask)
                });
                
                if (response.ok) {
                    const modal = bootstrap.Modal.getInstance(document.getElementById('taskModal'));
                    modal.hide();
                    loadTasks();
                }
            } catch (error) {
                console.error('保存任务失败:', error);
            }
        }
        
        // 缩放功能
        function zoomIn() {
            zoomLevel = Math.min(zoomLevel * 1.2, 3);
            renderGantt();
        }
        
        function zoomOut() {
            zoomLevel = Math.max(zoomLevel / 1.2, 0.5);
            renderGantt();
        }
        
        function resetZoom() {
            zoomLevel = 1;
            renderGantt();
        }
        
        // 导出功能
        function exportExcel() {
            window.location.href = '/api/export/excel';
        }
        
        function exportImage() {
            // 使用html2canvas导出图片
            alert('图片导出功能需要安装html2canvas库。\n\n当前版本支持Excel导出，图片导出可作为扩展功能实现。');
        }
    </script>
</body>
</html>
